<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>收货地址管理</title>
    <link rel="stylesheet" type="text/css" href="./css/webbase2.css"/>
    <!-- 自定义 Tailwind 配置 -->
    <link rel="stylesheet" type="text/css" href="./css/top-nav-optimized.css"/>
    <link rel="stylesheet" type="text/css" href="./css/webbase.css"/>
    <!-- 引入Font Awesome图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="./css/top-nav-optimized.css"/>
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.8;
            color: #333;
            background-color: #f8fafc;
            min-height: 100vh;
        }

        /* 导航栏样式 - 与message.html保持一致 */
        .nav-logo i {
            color: #3498db;
        }

        .nav-links {
            display: flex;
            list-style: none;
            gap: 25px;
        }

        .nav-links li a {
            color: white;
            text-decoration: none;
            font-size: 0.95rem;
            font-weight: 500;
            padding: 5px 0;
            position: relative;
            transition: color 0.3s ease;
        }

        .nav-links li a:hover {
            color: #3498db;
        }

        .nav-links li a::after {
            content: '';
            position: absolute;
            width: 0;
            height: 2px;
            bottom: 0;
            left: 0;
            background-color: #3498db;
            transition: width 0.3s ease;
        }

        .nav-links li a:hover::after {
            width: 100%;
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-menu .icon-btn {
            background: none;
            border: none;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            transition: color 0.3s ease;
        }

        .user-menu .icon-btn:hover {
            color: #3498db;
        }

        /* 主内容区样式 */
        .container {
            max-width: 1000px;
            margin: 40px auto;
            padding: 0 20px;
        }

        h1 {
            color: #1e293b;
            margin-bottom: 30px;
            padding-bottom: 12px;
            border-bottom: 3px solid #3b82f6;
            font-size: 1.8rem;
            display: flex;
            align-items: center;
        }

        h1 i {
            color: #3b82f6;
            margin-right: 12px;
            font-size: 1.5rem;
        }

        /* 地址列表样式 */
        .address-list {
            background-color: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            margin-bottom: 30px;
            position: relative;
        }

        .address-list::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(90deg, #3b82f6, #818cf8);
        }

        .address-header {
            padding: 20px 30px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .address-filters {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .select-all {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #475569;
            font-weight: 500;
        }

        .select-all input {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .address-item {
            padding: 25px 30px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            align-items: flex-start;
            gap: 15px;
            transition: background-color 0.3s ease;
        }

        .address-item:hover {
            background-color: #f8fafc;
        }

        .address-item:last-child {
            border-bottom: none;
        }

        .address-select {
            margin-top: 5px;
        }

        .address-select input {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }

        .address-content {
            flex: 1;
        }

        .address-contact {
            font-weight: 600;
            margin-bottom: 8px;
            display: flex;
            gap: 20px;
        }

        .address-details {
            color: #475569;
            margin-bottom: 12px;
        }

        .address-actions {
            display: flex;
            gap: 15px;
        }

        .address-action-btn {
            background: none;
            border: none;
            color: #3b82f6;
            cursor: pointer;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 5px;
            transition: color 0.3s ease;
        }

        .address-action-btn:hover {
            color: #2563eb;
        }

        .address-action-btn.delete {
            color: #ef4444;
        }

        .address-action-btn.delete:hover {
            color: #dc2626;
        }

        .address-default {
            display: inline-block;
            background-color: #f0fdf4;
            color: #166534;
            font-size: 0.8rem;
            padding: 2px 8px;
            border-radius: 4px;
            margin-left: 10px;
        }

        /* 空状态样式 */
        .empty-state {
            padding: 60px 20px;
            text-align: center;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 20px;
            color: #cbd5e1;
        }

        .empty-state p {
            margin-bottom: 20px;
            font-size: 1.1rem;
        }

        /* 按钮样式 */
        .button-group {
            margin: 20px 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .action-button {
            padding: 13px 28px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .action-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
        }

        .action-button:active {
            transform: translateY(-1px);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
        }

        .add-button {
            background-color: #10b981;
            color: white;
        }

        .add-button:hover {
            background-color: #059669;
        }

        .delete-selected-button {
            background-color: #ef4444;
            color: white;
        }

        .delete-selected-button:hover {
            background-color: #dc2626;
        }

        .back-button {
            background-color: #64748b;
            color: white;
        }

        .back-button:hover {
            background-color: #475569;
        }

        /* 弹窗样式 */
        #addressModal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 16px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from { transform: translateY(-20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .modal-title {
            margin-bottom: 20px;
            color: #1e293b;
            display: flex;
            align-items: center;
        }

        .modal-title i {
            color: #3b82f6;
            margin-right: 10px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #475569;
        }

        .form-group label i {
            color: #3b82f6;
            margin-right: 8px;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .nav-links {
                display: none;
            }

            .address-header, .button-group {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .address-filters {
                width: 100%;
            }

            .action-button {
                width: 100%;
            }

            .address-item {
                padding: 20px 15px;
            }

            .address-contact {
                flex-direction: column;
                gap: 5px;
            }

            h1 {
                font-size: 1.5rem;
            }

            .form-actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<!-- 保持与message.html相同的导航栏结构 -->
<div id="app">
    <top></top>
</div>
<body>
<div class="container">
    <h1><i class="fas fa-map-marker-alt"></i>收货地址管理</h1>

    <div class="button-group">
        <button class="action-button add-button" onclick="showAddAddressForm()">
            <i class="fas fa-plus"></i>新增收货地址
        </button>
        <div>
            <button class="action-button delete-selected-button" onclick="deleteSelectedAddresses()">
                <i class="fas fa-trash"></i>删除选中地址
            </button>
            <button class="action-button back-button" onclick="goBack()">
                <i class="fas fa-arrow-left"></i>返回
            </button>
        </div>
    </div>

    <div class="address-list">
        <div class="address-header">
            <div class="address-filters">
                <div class="select-all">
                    <input type="checkbox" id="selectAll">
                    <label for="selectAll">全选</label>
                </div>
            </div>
        </div>

        <div id="addressItems">
            <!-- 地址项将通过JavaScript动态生成 -->
        </div>

        <div id="emptyState" class="empty-state" style="display: none;">
            <i class="fas fa-box-open"></i>
            <p>您还没有添加任何收货地址</p>
            <button class="action-button add-button" onclick="showAddAddressForm()">
                <i class="fas fa-plus"></i>添加收货地址
            </button>
        </div>
    </div>
</div>

<!-- 新增/编辑地址弹窗 -->
<div id="addressModal">
    <div class="modal-content">
        <h2 class="modal-title">
            <i class="fas fa-map-marker-alt"></i>
            <span id="modalTitle">新增收货地址</span>
        </h2>

        <form id="addressForm">
            <input type="hidden" id="addressId">

            <div class="form-group">
                <label>
                    <i class="fas fa-user"></i>联系人
                </label>
                <input type="text" id="contact" class="form-control" required placeholder="请输入联系人姓名">
            </div>

            <div class="form-group">
                <label>
                    <i class="fas fa-phone"></i>手机号码
                </label>
                <input type="tel" id="mobile" class="form-control" required placeholder="请输入手机号码">
            </div>

            <div class="form-group">
                <label>
                    <i class="fas fa-map"></i>省份
                </label>
                <input type="text" id="province" class="form-control" required placeholder="请输入省份">
            </div>

            <div class="form-group">
                <label>
                    <i class="fas fa-map"></i>城市
                </label>
                <input type="text" id="city" class="form-control" required placeholder="请输入城市">
            </div>

            <div class="form-group">
                <label>
                    <i class="fas fa-map"></i>县/区
                </label>
                <input type="text" id="town" class="form-control" required placeholder="请输入县/区">
            </div>

            <div class="form-group">
                <label>
                    <i class="fas fa-home"></i>详细地址
                </label>
                <textarea id="street" class="form-control" required rows="3" placeholder="请输入详细地址"></textarea>
            </div>

            <div class="form-actions">
                <button type="button" class="action-button back-button" onclick="closeModal()">取消</button>
                <button type="submit" class="action-button add-button">保存地址</button>
            </div>
        </form>
    </div>
</div>

<script>
    // 存储当前地址列表
    let addressList = [];

    // 页面加载时获取地址列表
    window.onload = function() {
        fetchAddresses();
        initEventListeners();
    };

    // 初始化事件监听器
    function initEventListeners() {
        // 全选复选框事件
        document.getElementById('selectAll').addEventListener('change', function(e) {
            const checkboxes = document.querySelectorAll('.address-select input');
            checkboxes.forEach(checkbox => {
                checkbox.checked = e.target.checked;
            });
        });

        // 地址表单提交事件
        document.getElementById('addressForm').addEventListener('submit', function(e) {
            e.preventDefault();
            saveAddress();
        });
    }

    // 获取地址列表
    function fetchAddresses() {
        axios.get('http://localhost:8080/addresses/address')
            .then(response => {
                if (response && response.data) {
                    console.log('获取地址失败:', response.data);
                    addressList = response.data || [];
                    renderAddressList();
                } else {
                    console.error('获取地址失败:', response.data);
                    console.error('获取地址失败:', response.data.success);
                    alert('获取地址失败: ' + (response.data?.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('获取地址列表失败:', error);
                alert('获取地址列表失败，请稍后重试。');
            });
    }

    // 渲染地址列表
    function renderAddressList() {
        const addressItemsContainer = document.getElementById('addressItems');
        const emptyState = document.getElementById('emptyState');

        addressItemsContainer.innerHTML = '';

        if (addressList.length === 0) {
            emptyState.style.display = 'block';
            return;
        }

        emptyState.style.display = 'none';

        addressList.forEach(address => {
            const addressItem = document.createElement('div');
            addressItem.className = 'address-item';
            addressItem.innerHTML = `
                <div class="address-select">
                    <input type="checkbox" data-id="${address.id}">
                </div>
                <div class="address-content">
                    <div class="address-contact">
                        <span>${address.contact}</span>
                        <span>${address.mobile}</span>
                        ${address.isDefault ? '<span class="address-default">默认地址</span>' : ''}
                    </div>
                    <div class="address-details">
                        ${address.province} ${address.city} ${address.town} ${address.street}
                    </div>
                    <div class="address-actions">

                        <button class="address-action-btn delete" onclick="deleteAddress(${address.id})">
                            <i class="fas fa-trash"></i>删除
                        </button>
                        ${!address.isDefault ? `<button class="address-action-btn" onclick="setDefaultAddress(${address.id})">
                            <i class="fas fa-star"></i>设为默认
                        </button>` : ''}
                    </div>
                </div>
            `;
            addressItemsContainer.appendChild(addressItem);
        });
    }

    // 显示新增地址表单
    function showAddAddressForm() {
        document.getElementById('modalTitle').textContent = '新增收货地址';
        document.getElementById('addressId').value = '';
        document.getElementById('addressForm').reset();
        document.getElementById('addressModal').style.display = 'flex';
    }

    // 编辑地址
    function editAddress(id) {
        const address = addressList.find(item => item.id === id);
        console.error(id,address)
        if (!address) return;

        document.getElementById('modalTitle').textContent = '编辑收货地址';
        document.getElementById('addressId').value = address.id;
        document.getElementById('contact').value = address.contact;
        document.getElementById('mobile').value = address.mobile;
        document.getElementById('province').value = address.province;
        document.getElementById('city').value = address.city;
        document.getElementById('town').value = address.town;
        document.getElementById('street').value = address.street;

        document.getElementById('addressModal').style.display = 'flex';
    }

    // 保存地址
    function saveAddress() {
        const id = document.getElementById('addressId').value;
        const contact = document.getElementById('contact').value;
        const mobile = document.getElementById('mobile').value;
        const province = document.getElementById('province').value;
        const city = document.getElementById('city').value;
        const town = document.getElementById('town').value;
        const street = document.getElementById('street').value;

        // 简单验证
        if (!contact || !mobile || !province || !city || !town || !street) {
            alert('请填写完整地址信息');
            return;
        }

        // 验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(mobile)) {
            alert('请输入有效的手机号码');
            return;
        }

        // 调用后端接口保存地址
        const params = {
            province: province,
            city: city,
            town: town,
            street: street,
            username: contact,  // 注意后端接口参数是username，对应前端的contact
            mobile: mobile
        };

        // 如果是编辑操作，添加id参数
        if (id) {
            params.id = id;
        }

        axios.put('http://localhost:8080/addresses/address', null, { params })
            .then(response => {
                if (response.data) {
                    alert(id ? '地址更新成功' : '地址添加成功');
                    closeModal();
                    fetchAddresses();  // 重新获取地址列表
                } else {
                    alert('操作失败: ' + (response.data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('保存地址失败:', error);
                alert('保存地址失败，请稍后重试。');
            });
    }

    // 设置默认地址
    function setDefaultAddress(id) {
        if (!confirm('确定要设为默认地址吗？')) {
            return;
        }

        axios.put('http://localhost:8080/addresses/is_default', null, {
            params: { id: id }
        })
            .then(response => {
                if (response.success) {

                    //alert('已设置为默认地址');
                    fetchAddresses();
                } else {
                    console.error('设置默认地址失败:', response.success);
                    alert('设置失败: ' + (response.data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('设置默认地址失败:', error);
                alert('设置默认地址失败，请稍后重试。');
            });
    }

    // 关闭弹窗
    function closeModal() {
        document.getElementById('addressModal').style.display = 'none';
    }

    // 删除单个地址
    function deleteAddress(id) {
        if (!confirm('确定要删除这个地址吗？')) {
            return;
        }

        deleteAddresses([id]);
    }

    // 删除选中的地址
    function deleteSelectedAddresses() {
        const checkboxes = document.querySelectorAll('.address-select input:checked');
        if (checkboxes.length === 0) {
            alert('请先选择要删除的地址');
            return;
        }

        if (!confirm(`确定要删除选中的${checkboxes.length}个地址吗？`)) {
            return;
        }

        const ids = Array.from(checkboxes).map(checkbox => parseInt(checkbox.getAttribute('data-id')));
        deleteAddresses(ids);
    }

    // 执行删除操作
    function deleteAddresses(ids) {
        axios.delete('http://localhost:8080/addresses/address', {
            params: {
                ids: ids.join(',')  // 将数组转换为逗号分隔的字符串
            }
        })
            .then(response => {
                if (response.data) {
                    alert('删除成功');
                    fetchAddresses();  // 重新获取地址列表
                } else {
                    alert('删除失败: ' + (response.data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('删除地址失败:', error);
                alert('删除地址失败，请稍后重试。');
            });
    }

    // 返回上一页
    function goBack() {
        window.history.back();
    }
</script>

<!-- 保持与message.html相同的脚本引入顺序 -->
<script src="./js/axios.min.js"></script>
<script src="./js/common.js"></script>
<script src="./js/vue.js"></script>
<script src="./js/top.js"></script>
<script>
    new Vue({
        el: "#app"
    });
</script>
</body>
</html>
